// pages/setmeal/setmeal.js
import { setmealApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'

const app = getApp()

Page({
  data: {
    loading: true,
    setmealId: null,
    setmeal: null,
    dishes: [],
    quantity: 1,
    cartCount: 0
  },

  onLoad(options) {
    const { id } = options
    this.setData({
      setmealId: id
    })
    
    this.loadSetmealDetail()
  },

  onShow() {
    // 更新购物车数量
    this.updateCartCount()
  },

  // 加载套餐详情
  async loadSetmealDetail() {
    try {
      this.setData({ loading: true })
      
      // 模拟套餐数据，实际应该调用API
      const mockSetmeal = {
        id: this.data.setmealId,
        name: '经典套餐',
        price: 58.00,
        image: '/images/setmeals/setmeal1.jpg',
        description: '包含主菜、配菜、汤品的经典套餐，营养搭配均衡，适合2-3人享用。',
        categoryId: 2,
        status: 1
      }
      
      // 模拟套餐包含的菜品
      const mockDishes = [
        {
          name: '宫保鸡丁',
          copies: 1,
          image: '/images/dishes/dish1.jpg',
          description: '经典川菜，麻辣鲜香'
        },
        {
          name: '麻婆豆腐',
          copies: 1,
          image: '/images/dishes/dish2.jpg',
          description: '四川传统名菜，嫩滑爽口'
        },
        {
          name: '紫菜蛋花汤',
          copies: 2,
          image: '/images/dishes/dish3.jpg',
          description: '清淡营养，老少皆宜'
        }
      ]
      
      this.setData({
        setmeal: mockSetmeal,
        dishes: mockDishes,
        loading: false
      })
      
      // 设置导航栏标题
      wx.setNavigationBarTitle({
        title: mockSetmeal.name
      })
    } catch (error) {
      console.error('加载套餐详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 更新购物车数量
  updateCartCount() {
    app.updateCartCount()
    this.setData({
      cartCount: app.globalData.cartCount
    })
  },

  // 增加数量
  increaseQuantity() {
    this.setData({
      quantity: this.data.quantity + 1
    })
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      })
    }
  },

  // 添加到购物车
  async addToCart() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.data.setmeal || this.data.setmeal.status !== 1) {
      wx.showToast({
        title: '商品暂不可购买',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '添加中...' })
      
      const res = await wx.request({
        url: `${app.globalData.baseUrl}/user/shoppingCart/add`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data: {
          setmealId: this.data.setmealId
        }
      })
      
      if (res.data.code === 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        this.updateCartCount()
      } else {
        throw new Error(res.data.msg || '添加失败')
      }
    } catch (error) {
      console.error('添加到购物车失败:', error)
      wx.showToast({
        title: error.message || '添加失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 立即购买
  async buyNow() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.data.setmeal || this.data.setmeal.status !== 1) {
      wx.showToast({
        title: '商品暂不可购买',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '处理中...' })
      
      // 先添加到购物车
      const addRes = await wx.request({
        url: `${app.globalData.baseUrl}/user/shoppingCart/add`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data: {
          setmealId: this.data.setmealId
        }
      })
      
      if (addRes.data.code === 1) {
        // 跳转到订单确认页面
        wx.navigateTo({
          url: '/pages/order/order'
        })
      } else {
        throw new Error(addRes.data.msg || '添加失败')
      }
    } catch (error) {
      console.error('立即购买失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 跳转到购物车
  goToCart() {
    if (!checkLoginAndRedirect()) return
    
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: `${this.data.setmeal.name} - 美味外卖`,
      path: `/pages/setmeal/setmeal?id=${this.data.setmealId}`,
      imageUrl: this.data.setmeal.image
    }
  }
})
